package ai.people.netmon.msgsearch.service.impl;

import ai.people.core.common.properties.elastic.ElasticIndex;
import ai.people.netmon.framework.domain.searchmsg.request.WarningMessageRequest;
import ai.people.netmon.framework.model.response.PageResponse;
import ai.people.netmon.msgsearch.domain.response.InfoDataResult;
import ai.people.netmon.msgsearch.service.SearchAfterServiceImpl;
import ai.people.netmon.msgsearch.service.WarningMessageService;
import ai.people.netmon.utils.StringPool;
import ai.people.netmon.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 警告消息服务impl
 *
 * @author yuanqinglong
 * @date 2022/8/13 16:32
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WarningMessageServiceImpl implements WarningMessageService {


    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 警告消息
     *
     * @param warningMessageRequest 警告消息请求
     * @return {@link PageResponse}<{@link InfoDataResult}>
     */
    @Override
    public PageResponse<InfoDataResult> warningMessage(WarningMessageRequest warningMessageRequest) {
        String searchKeywords = warningMessageRequest.getSearchKeywords();
        // 创建查询对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isNotEmpty(searchKeywords)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("content", searchKeywords));
        }

        // 查询平台
        String platform = ElasticIndex.getEsTemplateIndexName(warningMessageRequest.getPlatform());
        String label = warningMessageRequest.getLabel();
        if (StringUtils.isNotEmpty(label)) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("tag.tag.keyword", label.split(StringPool.COMMA)));
        } else {
            boolQueryBuilder.must(QueryBuilders.existsQuery("tag.tag"));
        }
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("date");
        boolean searchDate = false;
        String format = "yyyy-MM-dd'T'HH:mm:ss'+0800'";
        if (StringUtils.isNotEmpty(warningMessageRequest.getStartDate())) {
            rangeQuery.gte(SearchAfterServiceImpl.getDate(format, warningMessageRequest.getStartDate()));
            searchDate = true;
        }
        if (StringUtils.isNotEmpty(warningMessageRequest.getEndDate())) {
            rangeQuery.lt(SearchAfterServiceImpl.getDate(format, warningMessageRequest.getEndDate()));
            searchDate = true;
        }
        if (searchDate) {
            boolQueryBuilder.must(rangeQuery);
        }


        builder.withQuery(boolQueryBuilder);
        builder.withPageable(PageRequest.of(warningMessageRequest.getPageNo(), warningMessageRequest.getPageSize()));
        builder.withSort(SortBuilders.fieldSort("date").order(SortOrder.DESC));
        NativeSearchQuery query = builder.build();
        query.setTrackTotalHits(true);
        // 调用查询接口
        log.info("es query:{}", query.getQuery());
        SearchHits<Map> searchHits = elasticsearchRestTemplate.search(query, Map.class, IndexCoordinates.of(platform));
        List<SearchHit<Map>> hits = searchHits.getSearchHits();
        List<InfoDataResult> dataResultList = hits.stream().map(mapSearchHit -> InfoDataResult.build(mapSearchHit.getContent())).collect(Collectors.toList());
        return PageResponse.builder(dataResultList, searchHits.getTotalHits());
    }


}
